<template>
  <picker mode="selector" :range="pickerRange" :range-key="rangeKey" @change="handlePickerChange" class="picker">
    <view class="picker-content">
      <view class="text">{{ pickerValueLabel }}</view>
      <text :class="`icon ` + icon"></text>
    </view>
  </picker>
</template>

<script>
export default {
  name: "selector",
  data() {
    return {
      pickerValue: this.value,
      pickerModel: null
    }
  },
  props: {
    icon: String,
    value: String | Number,
    pickerRange: {
      type: Array,
      default: () => []
    },
    rangeKey: {
      type: String,
      default: "label"
    },
    valueKey: {
      type: String,
      default: "value"
    },
  },
  computed: {
    pickerValueLabel() {
      if (this.rangeKey && this.pickerModel)
        return this.pickerModel[this.rangeKey]
    },
  },
  methods: {
    handlePickerChange(e) {
      let value = e.detail.value
      let model = this.getModelFromSource({index: value});
      console.log(value)
      this.pickerModel = model;
      this.pickerValue = model[this.valueKey];
      this.$emit("select", model)
    },
    /**
     * 获取选择的对象
     * @param {{[index]:Number, [value]:*}} data
     * @return *
     */
    getModelFromSource(data) {
      let source = this.pickerRange
      let {index, value} = data;
      if (value !== undefined && value !== null) {
        for (let i = 0; i < source.length; i++) {
          let item = source[i]
          if (item[this.valueKey] == value) return item;
        }
        return {}
      }
      return source[index];
    },
  },
  watch: {
    pickerValue(val) {
      this.$emit("update:value", val)
      this.$emit("input", val)
    },
    value: {
      handler: function (val) {
        this.pickerValue = val;
        let model = this.getModelFromSource({value: val})
        if (model) this.pickerModel = model
      },
      immediate: true
    },
    pickerRange(val) {
      let model = this.getModelFromSource({value: this.value})
      if (model) this.pickerModel = model
    },
  },
}
</script>

<style scoped lang='scss'>
.picker {
  display: flex;
  align-items: center;

  .picker-content {
    display: flex;
    align-items: center;

    .text {
      font-size: r(28px);
      font-weight: 500;
      color: #1E1E1E;
      display: inline-block;
      min-width: r(50px);
      text-align: right;
    }

    .icon {
      margin-left: r(60px);
      font-size: r(28px);
      margin-top: r(6px);
    }
  }

}
</style>